<template>
  <el-dialog
    v-if="dialogShow"
    v-model="dialogShow"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    custom-class="mydialog"
    width="400px"
    :title="dialogTitle"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :label-width="formLabelWidth"
      label-position="top"
      size="small"
      :rules="formRules"
      :show-message="false"
    >
      <el-form-item>
        <span>应收最大额度：</span>
      </el-form-item>
      <el-form-item prop="quota">
        <el-row :gutter="20">
          <el-col
            :span="24"
            style="padding-left: 0px;"
          >
            <el-col :span="9">
              <el-radio
                v-model="formData.isLimit"
                :label="1"
                @change="isLimitChange"
              >设置最大额度</el-radio>
            </el-col>
            <el-col
              v-if="formData.isLimit===1"
              :span="15"
            >
              <el-input
                v-model="formData.quota"
                placeholder="设置应收最大额度"
                @input="formData.quota=formData.quota.replace(/^\.+|[^\d.]/g,'')"
              ><template #append>元</template></el-input>
            </el-col>
            <el-col
              v-if="validateMsg"
              :span="24"
            ><span style="color: #f56c6c;font-size:12px;line-height:18px">{{ validateMsg }}</span></el-col>
          </el-col>
          <el-col :span="24">
            <el-radio
              v-model="formData.isLimit"
              :label="0"
              @change="isLimitChange"
            >不限额</el-radio>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <div
        class="dialog-footer"
        style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
          class="border-btn"
          size="small"
          @click="close"
        >取消</el-button>
        <el-button
          class="main-btn"
          size="small"
          type="primary"
          @click="confirm"
        >提交审核</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  inject,
  reactive,
  ref,
  toRefs,
} from 'vue'
import { useRoute } from 'vue-router'

export default defineComponent({
  name: 'CreditSetting',
  props: {
    modeId: {
      type: Object,
      default: () => {},
    },
    mode: {
      type: String,
      default: 'agent',
    },
  },
  emits: ['onSuccess'],
  setup(props, context) {
    const api = inject('api')
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const formRef = ref(null)
    var reactiveData = reactive({
      types: 'create',
      dialogTitle: '设置信用',
      creditDetail: null,
      relationId: route.query.id ? Number(route.query.id) : 0,
      getForCredit: {
        relationId: props.modeId,
        creditType: props.mode,
      },
      filterData: {
        page: 1,
        pageSize: 100,
      },
      listData: [],
      validateMsg: '',
      formData: {
        isLimit: 1,
        quota: null,
        products: [],
      },
    })
    const quotaPass = (rule, value, callback) => {
      if (reactiveData.formData.isLimit === 0) {
        reactiveData.formData.quota = null
        reactiveData.validateMsg = ''
        callback()
      } else {
        if (value && value !== 0) {
          if (value > 0) {
            reactiveData.formData.quota = Number(value)
            reactiveData.validateMsg = ''
            callback()
          } else {
            reactiveData.validateMsg = '应收最大额度必须大于0'
            callback(new Error('应收最大额度必须大于0'))
          }
        } else {
          reactiveData.validateMsg = '请输入应收最大额度'
          callback(new Error('请输入应收最大额度'))
        }
      }
    }
    var formRules = reactive({
      quota: [
        { required: false, validator: quotaPass, trigger: 'blur' },
        {
          pattern:
            /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
          message: '请输入数字,可保留两位小数',
        },
      ],
    })
    var formLabelWidth = ref(180)
    var dialogShow = ref(false)
    const open = (data) => {
      reactiveData.types = data.types
      reactiveData.creditDetail = data.creditDetail
      if (data.modeId) {
        reactiveData.relationId = data.modeId
        reactiveData.getForCredit.relationId = data.modeId
      }
      if (data.creditDetail) {
        if (data.creditDetail.creditStatus === '2') {
          reactiveData.dialogTitle = '调整信用'
        } else {
          reactiveData.dialogTitle = '调整信用'
        }
        if (data.creditDetail.quota > 0) {
          reactiveData.formData.isLimit = 1
        }
        reactiveData.formData.quota = data.creditDetail.quota
      } else {
        reactiveData.dialogTitle = '设置信用'
      }
      dialogShow.value = true
    }
    const close = () => {
      dialogShow.value = false
      reactiveData.formData = {
        isLimit: 1,
        quota: null,
        products: [],
      }
    }
    const isLimitChange = () => {
      formRef.value.validateField('quota')
    }
    const isBatchSetupChange = () => {
      formRef.value.validateField('capacity')
    }
    const productsStore = (data) => {
      if (reactiveData.formData.batchSetup === 0) {
        data.products = reactiveData.listData.map((p) => {
          return { id: p.id, capacity: p.batchSetup === 0 ? 0 : p.capacity }
        })
      } else {
        data.products = reactiveData.listData.map((p) => {
          return {
            id: p.id,
            capacity: reactiveData.formData.capacity,
          }
        })
      }
    }
    const creditCrete = () => {
      var data = {
        relationId: reactiveData.relationId,
        creditType: props.mode,
        quota: Number(reactiveData.formData.quota),
        products: [],
      }
      api.common.CREDIT_CREATE(data).then((res) => {
        if (res.code === 0) {
          context.emit('onSuccess')
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const creditEdit = () => {
      var data = {
        id: reactiveData.creditDetail.id,
        relationId: reactiveData.relationId,
        creditType: props.mode,
        quota: Number(reactiveData.formData.quota),
        products: [],
      }
      api.common.CREDIT_EDIT(data).then((res) => {
        if (res.code === 0) {
          context.emit('onSuccess')
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const creditChange = () => {
      var data = {
        id: reactiveData.creditDetail.id,
        relationId: reactiveData.relationId,
        creditType: props.mode,
        quota: Number(reactiveData.formData.quota),
        products: [],
      }
      api.common.CREDIT_CHANGE(data).then((res) => {
        if (res.code === 0) {
          context.emit('onSuccess')
          close()
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }
    const confirm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          if (reactiveData.types === 'create') {
            creditCrete()
          } else if (reactiveData.types === 'edit') {
            creditEdit()
          } else if (reactiveData.types === 'change') {
            creditChange()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
    const getList = () => {
      api.common.CREDIT_PRODUCT_LIST(reactiveData.getForCredit).then((res) => {
        if (res.code === 0) {
          const list = res.data.list || []
          reactiveData.total = res.data.total
          list.forEach((item, index) => {
            if (item.capacity === 0) {
              item.batchSetup = 0
            } else {
              item.batchSetup = 1
            }
          })
          reactiveData.listData = list
          console.log(reactiveData.listData)
        }
      })
    }
    return {
      formRef,
      ...toRefs(reactiveData),
      formRules,
      isBatchSetupChange,
      isLimitChange,
      formLabelWidth,
      dialogShow,
      open,
      close,
      confirm,
    }
  },
})
</script>
